package com.business.exam.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.net.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhanglele
 * @since 2023/11/17
 */
@Component
public class GeneratorSnowflake {
    private static final Logger logger = LoggerFactory.getLogger(GeneratorSnowflake.class);

    private long workerId = 0;  //第几号机房
    private long datacenterId = 1;  //第几号机器
    private Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);

    @PostConstruct  //构造后开始执行，加载初始化工作
    public void init(){
        try{
            //获取本机的ip地址编码

            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            logger.info("当前机器的workerId: " + workerId);
        }catch (Exception e){
            e.printStackTrace();
            logger.warn("当前机器的workerId获取失败 ----> " + e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized String snowflakeId(){
        return snowflake.nextId()+"";
    }


    public synchronized long snowflakeId(long workerId, long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }

    //测试
    public static void main(String[] args) {

        List<String> alist = new ArrayList<>();
        alist.add("1");
        alist.add("2");

        System.out.println(alist.stream().collect(Collectors.joining(",")));   //1428025721380536320S
    }
}
